﻿using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Fuse8.ContentManagementFramework.BizFacade.Services.Contents.Queryable
{
    public static class ExpressionVisitorExtensions
    {
         public static T GetValueFromConst<T>(this ConstantExpression exp, string name = null) where T : class
         {
             object val;
             object value = exp.Value;

             if (string.IsNullOrEmpty(name))
             {
                 val = value;
             }
             else
             {
                 Type type = exp.Type;
                 var info = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                 if (info != null)
                 {
                     val = info.GetValue(value);
                 }
                 else
                 {
                     var propInfo = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                     if (propInfo != null)
                     {
                         val = propInfo.GetValue(value, null);
                     }
                     else
                     {
                         val = null;
                     }
                 }
             }

             return val as T;
         }
    }
}